import sys
import time
from chengxu.main_module import CameraModule, OCRModule, DisplayModule, VoiceModule, gpio_handler

TINGZHI_FLAG_PATH = "task_file/tingzhi_flag"
_QUESTION_TEMPLATE_CACHE = None  # 题目模板缓存
_FLAG_INITIALIZED = False  # 标志文件初始化状态


def initialize_system():
    """系统初始化函数，确保标志文件和题目模板只初始化一次"""
    global _QUESTION_TEMPLATE_CACHE, _FLAG_INITIALIZED

    # 初始化停止标志
    if not _FLAG_INITIALIZED:
        with open(TINGZHI_FLAG_PATH, "w") as f:
            f.write("False")
        _FLAG_INITIALIZED = True  # 标记为已初始化

    # 初始化题目模板缓存
    if _QUESTION_TEMPLATE_CACHE is None:
        try:
            with open("task_file/tzrweml/T2TM.txt", "r", encoding="utf-8") as file:
                _QUESTION_TEMPLATE_CACHE = file.read().strip()
        except FileNotFoundError:
            _QUESTION_TEMPLATE_CACHE = "既是5的倍数又是7的倍数"

    return _QUESTION_TEMPLATE_CACHE


def run_paizhao(client, display_module, voice_module):
    """独立后的拍照验证逻辑（显式传递依赖）"""
    question_template = initialize_system()  # 调用初始化函数

    try:
        camera = CameraModule()
        ocr_module = OCRModule()
        max_attempts = 2
        recognized_text = ""

        # 拍照和OCR重试逻辑
        for attempt in range(max_attempts):
            filename = camera.capture_photo(is_extension_task_two=True)
            recognized_text = ocr_module.ocr_image_to_text(filename).strip().replace("\n", "").replace(" ", "")
            print(recognized_text)
            if recognized_text:
                break
            time.sleep(1)  # 重试间隔
        else:
            recognized_text = ""  # 两次尝试均失败


        # 判断识别结果
        if not recognized_text:
            answer = "错"
            pass
        else:
            # 构造查询
            query = f"{recognized_text}{question_template}，对不对？请用一个字回答：对/错"
            print(query)
            try:
                # 调用大模型验证
                response = client.chat.completions.create(
                    #model='Pro/deepseek-ai/DeepSeek-V3',
                    model='Qwen/Qwen2.5-72B-Instruct-128K',
                    messages=[{"role": "user", "content": query}],
                    temperature=0
                )
                answer = response.choices[0].message.content.strip().lower()
                print(answer)
            except Exception as e:
                print(f"API调用失败: {str(e)}")
                answer = "错"

        # 处理验证结果
        if "对" in answer:
            with open(TINGZHI_FLAG_PATH, "w") as f:
                f.write("True")
            #success_text = f"{recognized_text}{question_template}".replace('\n', '')
            with open("task_file/tzrweml/T2DA.txt", "r", encoding="utf-8") as file:
                template = file.read().strip()
                success_text = template.format(recognized_text=recognized_text)
            display_module.display_text_and_play_audio(success_text, voice_module)
            time.sleep(1)
            if hasattr(camera, 'cap') and camera.cap.isOpened():
                camera.cap.release()
            sys.exit(0)

        # 间隔3秒
        time.sleep(3)

    except Exception as e:
        print(f"程序异常: {str(e)}")
    finally:
        if 'camera' in locals() and hasattr(camera, 'cap') and camera.cap.isOpened():
            camera.cap.release()

